package com.rykj.energy.database.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rykj.energy.common.enums.StateType;
import com.rykj.energy.common.utils.*;
import com.rykj.energy.database.mapper.MeterDataMapper;
import com.rykj.energy.database.mapper.MeterMapper;
import com.rykj.energy.database.mapper.OrganizationMapper;
import com.rykj.energy.database.mapper.RotationMapper;
import com.rykj.energy.database.pojo.BasicMeter;
import com.rykj.energy.database.pojo.BasicMeterData;
import com.rykj.energy.database.pojo.BusinessRotation;
import com.rykj.energy.database.pojo.vo.MeterInfoVo;
import com.rykj.energy.database.service.IMeterService;
import lombok.extern.slf4j.Slf4j;
import net.anumbrella.seaweedfs.core.FileTemplate;
import net.anumbrella.seaweedfs.core.file.FileHandleStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@Service("meterService")
@Slf4j
public class MeterServiceImpl extends BaseService<MeterMapper, BasicMeter> implements IMeterService {

    @Autowired
    private MeterMapper meterMapper;

    @Autowired
    private MeterDataMapper meterDataMapper;

    @Autowired
    private OrganizationMapper orgMapper;

    @Autowired
    private RotationMapper rotationMapper;

//    @Autowired
//    private MeterResultDetailMapper meterResultDetailMapper;

    @Value("${file.upload:/data/rykj-energy/images}")
    private String savePicturePath;

    @Autowired
    @Lazy
    private FileTemplate template;

    @Override
    public BasicMeter findOneById(Integer meterId) {
        return meterMapper.selectById(meterId);
    }

    @Override
    public void saveMeter(BasicMeter basicMeter) {
        basicMeter.setCreateDate(new Date());
        basicMeter.setDelStatus(StateType.NORMAL.getCode());
        if(StringUtils.isNotEmpty(basicMeter.getRectSeat())){
            basicMeter.setMeterImgUrl(cutImgByRectSeat(basicMeter.getMeterImgUrl(),basicMeter.getDistType(),basicMeter.getRectSeat()));
        }
        meterMapper.insert(basicMeter);
        List<BasicMeterData> meterDatas =basicMeter.getMeterDatas();
        if(CollectionUtils.isNotEmpty(meterDatas)){
            for (BasicMeterData meterData:meterDatas) {
                meterData.setMeterId(basicMeter.getId());
                meterDataMapper.insert(meterData);
            }
        }
        if("Y".equals(basicMeter.getIsPageShow())&&StringUtils.isNotEmpty(basicMeter.getRepShowPageId())){
            BasicMeter repMeter=meterMapper.selectById(basicMeter.getRepShowPageId());
            repMeter.setIsPageShow("N");
            meterMapper.updateById(repMeter);
        }
    }

    @Override
    public void updateMeter(BasicMeter basicMeter) {
        BasicMeter meterInfo= meterMapper.selectById(basicMeter.getId());
        if(StringUtils.isEmpty(basicMeter.getCameraId())){
            meterInfo.setCameraId(null);
        }
        BeanUtils.copyProperties(basicMeter,meterInfo);
        if(StringUtils.isNotEmpty(basicMeter.getRectSeat())){
            meterInfo.setMeterImgUrl(cutImgByRectSeat(basicMeter.getMeterImgUrl(),basicMeter.getDistType(),basicMeter.getRectSeat()));
        }
        meterMapper.updateById(meterInfo);
        List<BasicMeterData > meterDatas =basicMeter.getMeterDatas();
        if(CollectionUtils.isNotEmpty(meterDatas)){
            //1.未传入的要先删除数据定义
            List<Integer> dataIds = new ArrayList<>();
            for (BasicMeterData meterData:meterDatas) {
                if(StringUtils.isNotEmpty(meterData.getId())){
                    dataIds.add(meterData.getId());
                }
            }
            if(CollectionUtils.isNotEmpty(dataIds)){
                meterDataMapper.deleteNotExitsIds(meterInfo.getId(),dataIds);
            }
            //2.再新增修改数据定义
            for (BasicMeterData meterData:meterDatas) {
                if(StringUtils.isEmpty(meterData.getId())){
                    meterData.setMeterId(meterInfo.getId());
                    meterDataMapper.insert(meterData);
                    continue;
                }
                BasicMeterData meterDataInfo =meterDataMapper.selectById(meterData.getId());
                BeanUtils.copyProperties(meterData,meterDataInfo);
                meterDataInfo.setMeterId(basicMeter.getId());
                meterDataMapper.updateById(meterDataInfo);
            }
        }
        if("Y".equals(basicMeter.getIsPageShow())&&StringUtils.isNotEmpty(basicMeter.getRepShowPageId())&&
        !meterInfo.getId().equals(basicMeter.getRepShowPageId())){
            BasicMeter repMeter=meterMapper.selectById(basicMeter.getRepShowPageId());
            repMeter.setIsPageShow("N");
            meterMapper.updateById(repMeter);
        }
    }

    @Override
    public void deleteMeters(Integer meterId) {
        BasicMeter meterInfo= meterMapper.selectById(meterId);
        meterInfo.setDelStatus(StateType.DELETED.getCode());
        meterMapper.updateById(meterInfo);
    }

    @Override
    public IPage<MeterInfoVo> getMeterPages(Integer pageNum, Integer pageSize, Integer orgId, String searchName, String meterType) {
        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgMapper.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        Page<BasicMeter> page=new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<MeterInfoVo> meterPage = meterMapper.getMeterPages(page, orgIds,searchName,meterType);
        if(CollectionUtils.isNotEmpty(meterPage.getRecords())){
            for (MeterInfoVo meter:meterPage.getRecords()) {
                List<BasicMeterData> meterDatas =meterDataMapper.selectByMeterId(meter.getId());
               meter.setMeterDatas(meterDatas);
            }
        }
        return meterPage;
    }

    @Override
    public List<BasicMeter> getShowPageMeters(Integer orgId) {
        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgMapper.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        return meterMapper.getShowPageMeters(orgIds);
    }

    @Override
    public  List<BusinessRotation> getRotationByUserId(Integer userId) {
        List<BusinessRotation> retMaps = rotationMapper.getRotationsByUserId(userId);
        return retMaps;
    }

    @Override
    public IPage<BusinessRotation> getRotationPageByUserId(Integer pageNum, Integer pageSize, Integer orgId, Integer userId) {

        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgMapper.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        Page<BusinessRotation> page=new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<BusinessRotation> rotationIPage = rotationMapper.getRotationPageByUserId(page,orgIds,userId);
//        if(CollectionUtils.isNotEmpty(rotationIPage.getRecords())){
//            for (BusinessRotation rotation:rotationIPage.getRecords()) {
//                List<MeterResultDetail> datas = meterResultDetailMapper.findTop1ResultDetails(rotation.getMeterId());
//                rotation.setResultDetailList(datas);
//            }
//        }
        return rotationIPage;
    }

    @Override
    public void saveRotationMeters(Integer userId,List<BusinessRotation> rotations) {
        Map params = new HashMap<>();
        params.put("userId",userId);
        rotationMapper.deleteByMap(params);
        for (BusinessRotation rotation:rotations) {
           rotationMapper.insert(rotation);
        }
    }

    @Override
    public void updateRotationMeters(List<BusinessRotation> rotations) {
        for(BusinessRotation rotation : rotations){
            rotationMapper.updateById(rotation);
        }
    }

    @Override
    public void deleteExecutorGroups(String rotationIds) {
        List<String> rotIds =   Arrays.asList(rotationIds.split(","));
        rotationMapper.deleteBatchIds(rotIds);
    }

    @Override
    public List<BasicMeterData> getMeterDatesByMeterId(Integer meterId) {
        return meterDataMapper.selectByMeterId(meterId);
    }

    @Override
    public IPage<BasicMeter> getNotRotationMeters(Integer pageNum, Integer pageSize, Integer orgId, String searchName, String meterType,Integer userId) {
        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgMapper.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        Page<BasicMeter> page=new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<BasicMeter> meterPage = meterMapper.getNotRotationMeters(page, orgIds,searchName,meterType, userId);
        if(CollectionUtils.isNotEmpty(meterPage.getRecords())){
            for (BasicMeter meter:meterPage.getRecords()) {
                List<BasicMeterData> meterDatas =meterDataMapper.selectByMeterId(meter.getId());
                meter.setMeterDatas(meterDatas);
            }
        }
        return meterPage;
    }

    @Override
    public BasicMeterData findMeterDataById(Integer resultDetailId) {
        return meterDataMapper.selectById(resultDetailId);
    }


    @Override
    public IPage<BasicMeter> getMeterForTasks(Integer pageNum, Integer pageSize, Integer orgId, String searchName, String meterType) {
        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgMapper.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        Page<BasicMeter> page=new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<BasicMeter> meterIPage = meterMapper.getMeterForTasks(page, orgIds,searchName,meterType);
        return meterIPage;
    }

    @Override
    public String cutImgByRectSeat(String imgUrl,String distType, String rectSeat) {
        try {
            String picName = ShortUUID.generateShortUuid()+System.currentTimeMillis()+".jpg";
            String picPath=savePicturePath + File.separator + DateUtils.getDateToDay(new Date()) + File.separator + distType+File.separator +"rect";
            FileUtils.mkdir(picPath);//文件夹不存在，则创建
//            RectSeatVo rectSeatVo =new RectSeatVo();
//            rectSeatVo.setFileUrl(imgUrl);
//            rectSeatVo.setSuffix("jpg");
//            rectSeatVo.setTargetFile(picPath+File.separator+picName);
//            JSONObject rectObj=JSONObject.parseObject(rectSeat);
//            rectSeatVo.setStartX(rectObj.getInteger("startX"));
//            rectSeatVo.setStartY(rectObj.getInteger("startY"));
//            rectSeatVo.setWidth(rectObj.getInteger("width"));
//            rectSeatVo.setHeight(rectObj.getInteger("height"));
//            AlgorithmImageUtil.cutImgROI(rectSeatVo);
            File file = new File(picPath + File.separator + picName);
            FileHandleStatus fileHandle = null;
            fileHandle = template.saveFileByStream(picName, new FileInputStream(file));
            imgUrl=fileHandle.getFileUrl();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgUrl;
    }

    @Override
    public List<BasicMeter> getMetersByCameraId(Integer cameraId) {
        Map<String,Object> comMap =new HashMap<>();
        comMap.put("delStatus", StateType.NORMAL.getCode());
        comMap.put("cameraId",cameraId);
        return meterMapper.selectByMap(comMap);
    }

    @Override
    public List<Map<String, Object>> getAlarmValues(Integer taskId, Integer cameraId) {
        return meterMapper.getAlarmValues(taskId,cameraId);
    }
}
